#include "stdafx.h"
#include "net/HostEntry.hpp"
#include "stdlib/bugcheck.hpp"
using namespace JHCPP::stdlib;
#include <algorithm>

NET_NAMESPACE_BEGIN

CHostEntry::CHostEntry()
{
}

CHostEntry::CHostEntry(struct hostent* entry)
{
	jh_check_ptr (entry);

	m_name = entry->h_name;	
	char** alias = entry->h_aliases;
	if (alias)
	{
		while (*alias)
		{
			m_aliases.push_back(std::string(*alias));
			++alias;
		}
	}
	char** address = entry->h_addr_list;
	if (address)
	{
		while (*address)
		{
			m_addresses.push_back(CIPAddress(*address, entry->h_length));
			++address;
		}
	}
}

#if defined(JH_HAVE_IPv6)
CHostEntry::CHostEntry(struct addrinfo* ainfo)
{
	jh_check_ptr (ainfo);

	for (struct addrinfo* ai = ainfo; ai; ai = ai->ai_next)
	{
		if (ai->ai_canonname)
		{
			m_name.assign(ai->ai_canonname);
		}
		if (ai->ai_addrlen && ai->ai_addr)
		{
			switch (ai->ai_addr->sa_family)
			{
			case AF_INET:
				m_addresses.push_back(CIPAddress(&reinterpret_cast<struct sockaddr_in*>(ai->ai_addr)->sin_addr, sizeof(in_addr)));
				break;
			case AF_INET6:
				m_addresses.push_back(CIPAddress(&reinterpret_cast<struct sockaddr_in6*>(ai->ai_addr)->sin6_addr, sizeof(in6_addr), reinterpret_cast<struct sockaddr_in6*>(ai->ai_addr)->sin6_scope_id));
				break;
			}
		}
	}
}
#endif

CHostEntry::CHostEntry(const CHostEntry& entry):
m_name(entry.m_name),
m_aliases(entry.m_aliases),
m_addresses(entry.m_addresses)
{
}

CHostEntry& CHostEntry::operator = (const CHostEntry& entry)
{
	if (&entry != this)
	{
		m_name      = entry.m_name;
		m_aliases   = entry.m_aliases;
		m_addresses = entry.m_addresses;
	}
	return *this;
}

void CHostEntry::swap(CHostEntry& hostEntry)
{
	std::swap(m_name, hostEntry.m_name);
	std::swap(m_aliases, hostEntry.m_aliases);
	std::swap(m_addresses, hostEntry.m_addresses);
}

CHostEntry::~CHostEntry()
{
}

NET_NAMESPACE_END
